﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint;

namespace SharePoint2010Poll
{
    public partial class ManagePoll : UserControl
    {
        public PollStates PollState
        {
            get
            {
                return (this.Parent as PollWebPart).PollState;
            }
            set
            {
                SPLimitedWebPartManager wpm =
                    SPContext.Current.Web.GetLimitedWebPartManager(Page.Request.Path, PersonalizationScope.Shared);
                try
                {
                    PollWebPart wp = wpm.WebParts[this.Parent.ID] as PollWebPart;
                    wpm.Web.AllowUnsafeUpdates = true;
                    wp.PollState = value;
                    wpm.SaveChanges(wp);
                }
                finally
                {
                    wpm.Web.AllowUnsafeUpdates = false;
                }
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            
            if (this.PollState == PollStates.PollConfigured)
            {               
                    LoadData();              
            }
        }
        private void LoadData()
        {
            EnsureChildControls();

            PollsItem poll = PollHelper.GetPoll(this.Parent.ID);
            if (poll != null)
            {
                txtPollTitle.Text = string.IsNullOrEmpty(poll.Title) ? string.Empty : poll.Title;
                txtPollQuestion.Text = string.IsNullOrEmpty(poll.Question) ? string.Empty : poll.Question;
                txtPollAnswers.Text = string.IsNullOrEmpty(poll.Answers) ? string.Empty : poll.Answers;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            EnsureChildControls();
            PollsItem newPoll = new PollsItem();

            newPoll.PollId = this.Parent.ID;
            newPoll.Title = txtPollTitle.Text;
            newPoll.Question = txtPollQuestion.Text;
            newPoll.Answers = txtPollAnswers.Text;

            PollHelper.CreatePoll(newPoll);
            this.PollState = PollStates.PollConfigured;
            LoadData();
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            this.Controls.Add(new LiteralControl(this.PollState.ToString()));
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {

        }
    }
}
